package com.atguigu.juc.t6;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class RedSpider {
    ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    //创建写的锁
    ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();
    //创建读的锁
    ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();

    public Object msg = "现在是11月底，尚硅谷6666666";
    //写的方法
    public void write(Object msg) {
        try {
            //获得write锁
            writeLock.lock();
            System.out.println(Thread.currentThread().getName() + "开始写的操作了");

            //对写操作进行1-3秒的操作
            try {
                TimeUnit.SECONDS.sleep( 1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + "写入完毕了，内容为：" + msg);
        } finally {
            //释放write锁
            writeLock.unlock();
        }
    }

    //读的方法
    public Object read() {
        try {
            readLock.lock();
            System.out.println(Thread.currentThread().getName() + "开始读取操作了...........");

            //对读操作进行1-3秒的操作
            try {
                TimeUnit.SECONDS.sleep(new Random().nextInt(3) + 1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + "读取完毕了");
            return msg;
        } finally {
            readLock.unlock();
        }
    }
}
